/*   
 * Copyright 2009-2010 Rob Schoening
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *    http://www.apache.org/licenses/LICENSE-2.0
 *    
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.beaconframework.util.xml;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;

import javax.xml.namespace.QName;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathVariableResolver;


public class VariableResolverRegistry implements XPathVariableResolver {

    private Map<QName, Object> map = new ConcurrentHashMap<QName, Object>();
    private List<XPathVariableResolver> resolvers = new CopyOnWriteArrayList<XPathVariableResolver>();

    public void attach(XPath xpath) {
        xpath.setXPathVariableResolver(this);
    }

    public void attach(XPathUtil xpu) {
        xpu.getXPath().setXPathVariableResolver(this);
    }

    public Object resolveVariable(QName variableName) {
        HashSet<XPathVariableResolver> set = new HashSet<XPathVariableResolver>();
        return resolveVariable(variableName, set);
    }

    private Object resolveVariable(QName variableName,
            Set<XPathVariableResolver> set) {
        set.add(this);
        Object val = map.get(variableName);
        if (val != null) {
            return val;
        }

        for (XPathVariableResolver r : resolvers) {
            if (!set.contains(r)) {
                if (r instanceof VariableResolverRegistry) {
                    VariableResolverRegistry vrr = (VariableResolverRegistry) r;
                    return vrr.resolveVariable(variableName, set);
                } else {
                    return r.resolveVariable(variableName);
                }
            }
        }
        return null;
    }

    public void addVariable(QName q, Object obj) {
        map.put(q, obj);
    }

    public void addVariable(String ns, String n, Object obj) {
        QName q = new QName(ns, n);
        addVariable(q, obj);
    }

    public void addXPathVariableResolver(XPathVariableResolver r) {
        if (r == null) {
            return;
        }
        resolvers.add(r);
    }
}
